<template>
  <div class="spaceUser">
    <h3>空间用户</h3>
    <n-divider class="spaceUser-divider" />
    <n-data-table
      :columns="columns"
      :data="spaceUser"
      :pagination="pagination"
      :bordered="false"
    />
  </div>
</template>

<script setup lang='ts'>
import { h, ref, onMounted } from 'vue'
import { NAvatar, NIcon, NButton, useDialog } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import manIcon from "../../assets/svg/manIcon.svg"
import womanIcon from "../../assets/svg/womanIcon.svg"
import { GetSpaceUser, exitSpace } from "../../api/space"

const dialog = useDialog()

type UserType = {
  id?: number,
  username: string,
  avatar: string,
  sex: string,
  sign: string,
  join_time: string,
  phone?: string,
  space_id?: number,
}

const props = defineProps<{
  spaceId: string
}>()

const pagination = ref<any>(false)

const createColumns = ({
  removeUser
}: {
  removeUser: (row: UserType) => void
}): DataTableColumns<UserType> => {
  return [
    {
      title: '头像',
      key: 'avatar',
      render (row) {
        return h(
          NAvatar,
          {
            round: true,
            src: 'api/' + row.avatar
          }
        )
      }
    },
    {
      title: '用户名',
      key: 'username',
    },
    {
      title: '性别',
      key: 'sex',
      render (row) {
        return h(
          NIcon,
          {
            component: () => h(
              'img',
              {
                src: row.sex == '男'?manIcon:womanIcon,
              },
            )
          },
        )
      }
    },
    {
      title: '个性签名',
      key: 'sign'
    },
    {
      title: '加入时间',
      key: 'join_time'
    },
    {
      title: '',
      key: 'action',
      render (row) {
        return h(
          NButton,
          {
            size: 'small',
            type: 'error',
            quaternary: true,
            onClick: () => removeUser(row)
          },
          {default : () => '移出空间'}
        )
      }
    },
  ]
}

const spaceUser = ref<UserType[]>([])


const columns = createColumns({
  removeUser (row: UserType) {
    dialog.warning({
      title: '警告',
      content: '确定将该用户移出空间吗？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        exitSpace({
          space_id: Number(props.spaceId),
          phone: row.phone
        })
        spaceUser.value = spaceUser.value.filter(item => item.id !== row.id)
      }
    })
  }
})


onMounted(async() => {
  const res_data = await GetSpaceUser(Number(props.spaceId))
  if(res_data.code === "200"){
    spaceUser.value = res_data.data.space_user
  }
})

</script>

<style lang='scss' scoped>
.spaceUser{
  width: 100%;
  min-height: 100%;
  padding: 0 30px;
  box-sizing: border-box;
  .spaceUser-divider{
    margin: 0 0 20px 0;
  }
}
</style>